package com.czwj.realm;

import java.util.Date;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;


/**
 * @author Like
 */
@Service
public class JwtService {

	@Value("${jwt.key}")
	private String key;
	@Value("${jwt.expire}")
	private Long expire;

	/**
	 * 创建token
	 *
	 * @param id
	 * @param subject
	 * @return
	 */
	public String createToken(String id, String subject) {
		long nowMillis = System.currentTimeMillis();
		Date now = new Date(nowMillis);
		JwtBuilder builder = Jwts.builder().setId(id).setSubject(subject).setIssuedAt(now)
				.signWith(SignatureAlgorithm.HS256, key);
		if (expire > 0) {
			builder.setExpiration(new Date(nowMillis + expire));
		}
		return builder.compact();
	}

	/**
	 * 解析token
	 *
	 * @param token
	 * @return
	 */
	public Claims parseToken(String token) {
		try {
			return Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody();
		} catch (Exception e) {
			return null;
		}
	}

}
